package com.example.demo.utils;

import lombok.extern.slf4j.Slf4j;
import org.docx4j.Docx4J;
import org.docx4j.convert.out.FOSettings;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.Mapper;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

import java.io.File;
import java.io.OutputStream;
import java.nio.file.Files;

/**
 * @author sdy
 * @description
 * @date 2025/3/15
 */
@Slf4j
public class FileTransferUtils {

    public static void main(String[] args) {
        FileTransferUtils.doc2Pdf("/Users/sdy/Desktop/input.docx", "/Users/sdy/Desktop/output.pdf");
    }

    public static void doc2Pdf(String input, String output) {
        doc2Pdf(new File(input), new File(output));
    }

    public static void doc2Pdf(File input, File output) {
        try (OutputStream os = Files.newOutputStream(output.toPath())) {
            // 加载文档
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(input);
            // 字体处理
            Mapper fontMapper = new IdentityPlusMapper();
            fontMapper.put("隶书", PhysicalFonts.get("LiSu"));
            fontMapper.put("宋体", PhysicalFonts.get("SimSun"));
            fontMapper.put("微软雅黑", PhysicalFonts.get("Microsoft YaHei"));
            fontMapper.put("黑体", PhysicalFonts.get("SimHei"));
            fontMapper.put("楷体", PhysicalFonts.get("KaiTi"));
            fontMapper.put("新宋体", PhysicalFonts.get("NSimSun"));
            wordMLPackage.setFontMapper(fontMapper);
            // 创建Fo输出配置
            FOSettings foSettings = Docx4J.createFOSettings();
            foSettings.setWmlPackage(wordMLPackage);
            // 输出到文件
            Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
            log.info("转换文件成功");
        } catch (Exception ex) {
            log.error("转换文件失败：{}", ex.getMessage(), ex);
            throw new RuntimeException("转换文件失败：" + ex.getMessage());
        }
    }

}
